package com.ztesoft.huangfu.learning.springboot.springbootrestful.controller;

import com.ztesoft.huangfu.learning.springboot.springbootrestful.entity.Student;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Author: huangfu.daohui
 * Date: 2018/5/23
 * Time: 16:56
 * Version: 1.0
 * Description: springboot入门
 * 启动项目，直接在url中访问http://127.0.0.1:8080/hi,建议用postman测试
 **/
@RestController
public class StudentController {


    static List<Student> stu = new ArrayList<Student>();

    // 或者 创建线程安全的Map
    //    private static Map<Long, User> users = Collections.synchronizedMap(new HashMap<Long, User>());
    public StudentController() {
        Student student1 = new Student();
        student1.setId(1);
        student1.setAge(12);
        student1.setName("zhangsan");
        Student student2 = new Student();
        student2.setId(2);
        student2.setAge(13);
        student2.setName("lisi");
        Student student3 = new Student();
        student3.setId(3);
        student3.setAge(14);
        student3.setName("wangwu");
        stu.add(student1);
        stu.add(student2);
        stu.add(student3);

    }

    //http://127.0.0.1:8080/hi
    @GetMapping("/hi")
    public String helloWorld() {
        return "hello world";
    }

    //http://127.0.0.1:8080/getStudentList
    @GetMapping("/getStudentList")
    public List<Student> getStudentList() {
        return stu;
    }

    //http://127.0.0.1:8080/getStudentById?id=1
    @GetMapping("/getStudentById")
    public Student getStudentById(Long id) {
        for (Student s : stu) {
            if (s.getId() == id) {
                return s;
            }
        }
        return null;
    }

    //http://127.0.0.1:8080/addStudent .body中添加参数
    @PostMapping("/addStudent")
    public List<Student> addStudent(Student s) {
        Student student = new Student();
        student.setId(s.getId());
        student.setName(s.getName());
        student.setAge(s.getAge());
        stu.add(student);
        return stu;
    }

    //http://127.0.0.1:8080/modifyStudent body中添加参数
    @PostMapping("/modifyStudent")
    public List<Student> modifyStudent(Long id, Student s) {
        for (Student ss : stu) {
            if (ss.getId() == id) {
                ss.setAge(s.getAge());
                ss.setName(s.getName());
            }
        }
        return stu;
    }

    // http://127.0.0.1:8080/delByStudentId?id=1
    @DeleteMapping("/delByStudentId")
    public List<Student> delStudent(Long id) {
        for (Student ss : stu) {
            if (ss.getId() == id) {
                stu.remove(ss);
            }
        }
        return stu;
    }

}
